package net.telesing.tcmc.core;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil
{

    private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    //private final static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat("yyyy-MM-dd");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>()
    {
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>()
    {
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    public static boolean isDate(String sdate)
    {
        return toDate(sdate) != null;
    }

    public static boolean isDatetime(String sdatetime)
    {
        return toDatetime(sdatetime) != null;
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate)
    {
        try
        {
            return dateFormater2.get().parse(sdate);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDatetime(String sdate)
    {
        try
        {
            return dateFormater.get().parse(sdate);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate)
    {
        Date time = toDate(sdate);
        if (time == null)
        {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        //判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate))
        {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
            {
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            }
            else
            {
                ftime = hour + "小时前";
            }
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0)
        {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
            {
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            }
            else
            {
                ftime = hour + "小时前";
            }
        }
        else if (days == 1)
        {
            ftime = "昨天";
        }
        else if (days == 2)
        {
            ftime = "前天";
        }
        else if (days > 2 && days <= 10)
        {
            ftime = days + "天前";
        }
        else if (days > 10)
        {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate)
    {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null)
        {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate))
            {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串。
     * 空白串是指由空格、制表符、回车符、换行符组成的字符串
     * 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input)
    {
        if (input == null || "".equals(input))
        {
            return true;
        }

        for (int i = 0; i < input.length(); i++)
        {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email)
    {
        if (email == null || email.trim().length() == 0)
        {
            return false;
        }
        return emailer.matcher(email).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue)
    {
        try
        {
            return Integer.parseInt(str);
        }
        catch (Exception e)
        {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj)
    {
        if (obj == null)
        {
            return 0;
        }
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj)
    {
        try
        {
            return Long.parseLong(obj);
        }
        catch (Exception e)
        {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b)
    {
        try
        {
            return Boolean.parseBoolean(b);
        }
        catch (Exception e)
        {
        }
        return false;
    }


    public static String left(String str, int length)
    {
        if (null == str)
        {
            return null;
        }
        int len = str.length();
        if (len <= length)
        {
            return str;
        }
        return str.substring(0, length);
    }

    public static String transferLike(String s)
    {
        if (null == s)
        {
            return null;
        }
        return "%" + s.trim().replace("%", "\\%") + "%";
    }

    public static String getExceptionStackTrace(Exception ex)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        return sw.toString();
    }

    public static String getFormatDate()
    {
        long c = System.currentTimeMillis();
        SimpleDateFormat format1 = new SimpleDateFormat();
        format1.applyPattern("yyyyMMdd");
        String date = format1.format(c);
        return date;
    }

    public static String getCurrentDate()
    {
        long c = System.currentTimeMillis();
        SimpleDateFormat format1 = new SimpleDateFormat();
        format1.applyPattern("yyyy-MM-dd");
        String date = format1.format(c);
        return date;
    }

    //add 孙一凡  appAction 所用
    /**
     * 判断是否是合法手机号码
     * @param phoneNumber
     * @return
     */
    public static boolean validatePhone(String phoneNumber)
    {
        String check = "^(13[0-9]|14[0-9]|15[0-9]|18[0-9])\\d{8}$";
        Pattern phoneRegex = Pattern.compile(check);
        Matcher phoneMatcher = phoneRegex.matcher(phoneNumber);
        boolean isMatched = phoneMatcher.matches();
        if(isMatched)
        {
            return isMatched;
        }
        return false;
    }
    public static boolean validPwd(String pwd){
        Pattern pattern = Pattern.compile("[\\x00-\\xFF]{6,16}");
        return pattern.matcher(pwd).matches();
    }
    public static boolean validMobile(String phone){
        Pattern pattern = Pattern.compile("^[1][0-9]{10}$");
        return pattern.matcher(phone).matches();
    }

    /**
     * 随机生成6位数字符
     * @param lenght
     * @return
     */
    public static String getCipher(int lenght)
    {
        String nice="";
        Random random=new Random();
        for(int i=0;i<lenght;i++)
        {
            String charOrNum=random.nextInt(2)%2==0?"char":"num";
            if("char".equalsIgnoreCase(charOrNum))
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
                nice += (char) (choice + random.nextInt(26));
            }
            else if("num".equalsIgnoreCase(charOrNum))
            {
                nice += String.valueOf(random.nextInt(10));
            }
        }
        return nice;
    }
    /**
     * 随机生成6位数字符
     * @param lenght
     * @return
     */
    public static String getVC(int lenght)
    {
        String nice="";
        Random random=new Random();
        for(int i=0;i<lenght;i++)
        {
            nice += String.valueOf(random.nextInt(10));

        }
        return nice;
    }



    public static java.sql.Date toDate(long date)
    {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.sql.Date dateTime=null;
        try
        {
            dateTime=new java.sql.Date(formatter.parse(formatter.format(date)).getTime());
        }
        catch (ParseException e)
        {
            e.printStackTrace();
            System.out.println("时间转换异常"+e.getMessage());
        }
        return dateTime;
    }
    public static String formatDate(Object date)
    {
        SimpleDateFormat isStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = isStart.format(date);
        return time;
    }

    public static Date strToDate(String dateTime) throws ParseException{
        SimpleDateFormat isStart = new SimpleDateFormat("yyyy-MM-dd");
        Date date = isStart.parse(dateTime);
        return date;
    }
    //add 孙一凡  appAction 所用



    public static List<String>  getSectionDate(long startTime,long endTime) throws Exception{
        double between = (endTime - startTime) / 1000;// 除以1000是为了转换成秒
        double day = between / (24 * 3600);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginDate = sdf.format(startTime);
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < day; i++) {
            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(beginDate));
            cd.add(Calendar.DATE, i);// 增加一天
            list.add(sdf.format(cd.getTime()));
        }
        return list;
    }

    public static List<Map<String,String>> getMapSectionDate(long startTime,long endTime) throws Exception{
         long between = (endTime - startTime) / 1000;// 除以1000是为了转换成秒
         int day =(int)( between / (24 * 3600))+1;
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String beginDate = sdf.format(startTime);
        if(day <= 14){
            return getListMap(day,1,beginDate,sdf,list);
        }else if(day >=15 && day <60){
            return getListMap((day/7+1),6,beginDate,sdf,list);
        }else if(day >=60){
            return getListMap((day/30+1),29,beginDate,sdf,list);
        }
        return null;
    }

    public static int diff(String beginDate,String endDate) throws Exception{
        long between = (StringUtil.strToDate(endDate).getTime() - StringUtil.strToDate(beginDate).getTime()) / 1000;// 除以1000是为了转换成秒
        return  (int)( between / (24 * 3600))+1;
    }

    public static List<Map<String,String>> getListMap(int count,int day,String beginDate,SimpleDateFormat sdf,List<Map<String,String>> list) throws Exception{
        for (int i = 0; i < count; i++) {
            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(beginDate));
            cd.add(Calendar.DATE, day);// 增加一天
            String nextDay = sdf.format(cd.getTime());
            Map<String,String> map = new HashMap<String,String>();
            map.put("current_date", beginDate);
            System.out.println(StringUtil.strToDate(nextDay).getTime() + "," + StringUtil.strToDate(StringUtil.getCurrentDate()).getTime());
            if(StringUtil.strToDate(nextDay).getTime() > StringUtil.strToDate(StringUtil.getCurrentDate()).getTime()){
                nextDay =  StringUtil.getCurrentDate();
            }
            map.put("next_date", nextDay);
            if(day != 1){
                map.put("date",beginDate+"到"+nextDay);
                cd.setTime(sdf.parse(nextDay));
                cd.add(Calendar.DATE, 1);// 增加一天
                beginDate = sdf.format(cd.getTime());
            }else {
                map.put("date",beginDate);
                beginDate = nextDay;

            }
            list.add(map);
            if(StringUtil.strToDate(beginDate).getTime() > StringUtil.strToDate(StringUtil.getCurrentDate()).getTime()){
                break;
            }
        }
        return list;
    }

    public static Date getNextDay(Date currentDate) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cd = Calendar.getInstance();
        cd.setTime(currentDate);
        cd.add(Calendar.DATE, 1);// 增加一天
        return sdf.parse(sdf.format(cd.getTime()));
    }

    public static String getNextDay(){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        Date date = calendar.getTime();
        return sdf.format(date);
    }


    /**
     * 判断是否是同一天的行为
     * @param createTime
     * @param nowTime
     * @return
     */
    public static boolean isSameDay(Date createTime,Date nowTime){
        if (createTime!=null&&nowTime!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String crate = sdf.format(createTime);
            String now = sdf.format(nowTime);
            if (crate.equals(now)){
                return false;
            } else {
                return true;//不是在同一天注册
            }
        }
        return true;
    }
    /**
     *  将相差时间 换算为小时
     * @param sentimes
     * @param nowtimes
     * @return
     */
    public static int getTimeDifference(Timestamp sentimes, Timestamp nowtimes) {
        SimpleDateFormat timeformat = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");
        long va1 = 0l, va2 = 0l;
        try {
            va1 = timeformat.parse(getTimeStampNumberFormat(sentimes)).getTime();
            va2 = timeformat.parse(getTimeStampNumberFormat(nowtimes)).getTime();
        } catch (ParseException e) {
        }
        int hours = (int) ((va1 - va2) / 3600000);
        int second = hours*3600;
        System.out.print("小时"+hours);
        System.out.print("秒"+second);
        return second;
    }

    /**
     *
     * @param formatTime
     * @return
     */
    public static String getTimeStampNumberFormat(Timestamp formatTime) {
        SimpleDateFormat m_format = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss", new Locale("zh", "cn"));
        return m_format.format(formatTime);
    }

    /**
     * 获取某个符号第n次出现的位置
     *
     * @param str
     * @param flag
     * @param n
     * @return
     *
     * Added By Zmt
     */
    public static int getPosition(String str, String flag, int n)
    {
        Matcher matcher = Pattern.compile(flag).matcher(str);
        int mIdx = 0;
        while(matcher.find())
        {
            mIdx++;
            if(mIdx == n)
                break;
        }
        return matcher.start();
    }

    /**
     * 判断当前操作系统是否为Linux
     *
     * @return
     *
     * Added By Zmt
     */
    public static boolean isLinux()
    {
        return "/".equals(System.getProperties().getProperty("file.separator"));
    }

}
